/*
 * This is the receiver part of the server
*/

package com.costeaalex.blueserver.server;

import java.util.ArrayList;
import java.util.Calendar;

import com.costeaalex.blueserver.communication.CommunicationManager;
import com.costeaalex.blueserver.pccontrollers.MouseController;
import com.costeaalex.blueserver.threads.MainThread;

public class BlueServerReceiver extends Thread
	{
	
	private boolean isRunning=false;
	private CommunicationManager cML;
	//private MainThread mTL;
	private byte[] data;
	private Calendar calendar=Calendar.getInstance();
	private long date=0;
	private boolean clientConnected=false;
	private ThreadManager tM;
	private ArrayList<CommandReceiver> commReceivers;
	private ArrayList<ArrayList<byte[]>> stacks;
	private int id=0;
	
	private BlueServerSync bSS;
	private ThreadControlDummyThread tCDT;
	
	private MouseController mC;
	
	public BlueServerReceiver(MainThread mT, CommunicationManager cM)
		{
		cML=cM;
		tM=new ThreadManager();
		stacks=new ArrayList<ArrayList<byte[]>>();
		commReceivers=new ArrayList<CommandReceiver>();
		bSS=new BlueServerSync(cML, tM);
		tCDT=new ThreadControlDummyThread(tM);
		mC=new MouseController();
		//mTL=mT;
		}
	
	@Override
	public void run()
		{
		isRunning=true;
		
		commReceivers.add(mC);
		stacks.add(null);
		
		bSS.start();
		tCDT.start();
		while(bSS.getState()!=Thread.State.WAITING || tCDT.getState()!=Thread.State.WAITING)
			{}
		tM.rotate(tCDT);
		
		while(isRunning)
			{
			data=new byte[10];
			if(cML.receiveBlock(data)>0)
				{
				if(data[0]==0)
					{
					serviceStarter(data);
					clientConnected=true;
					}
				else
					{
					if(data[0]==1 && data[1]==id && data[2]==0 && data[3]==2)
						{
						calendar=Calendar.getInstance();
						date=calendar.getTimeInMillis();
						}
					else
						{
						dispatchCommand(data);
						}
					}
				
				}
			}
		}
	
	private synchronized void dispatchCommand(byte[] command)
		{
		int i;
		if(command[0]==3)
			{
			cML.send(command);
			System.out.println("echo");
			}
		
		for(i=0; i<commReceivers.size(); i++)
			if(commReceivers.get(i).getReceiverId()==command[1])
				{
				if(stacks.get(i)==null)
					commReceivers.get(i).parseCommand(command);
				else
					stacks.get(i).add(command);
				break;
				}
		}
	
	private void serviceStarter(byte[] data)
		{
		if(data[0]==0)
			{
			switch(data[1])
				{
				case 5:{
						commReceivers.add(bSS);
						stacks.add(null);
						bSS.start();
						break;
						}
				}
			}
		}
	
	public boolean clientConnected()
		{
		return clientConnected;
		}
	
	public synchronized long getDate()
		{
		return date;
		}
	
	public void destroy()
		{
		isRunning=false;
		cML.stop();
		interrupt();
		}
	
	}
